package com.chen.shopping_manager_api.securityhandler;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {


        //自定义登录配置
        httpSecurity.formLogin(
                form -> {
                    form.usernameParameter("username") //获取用户名的对应参数
                            .passwordParameter("password") //获取密码的对应参数
                            .loginProcessingUrl("/admin/login") //登录的处理路径
                            .successHandler(new MyLoginSuccessHandler()) //登陆成功处理器
                            .failureHandler(new MyLoginFailureHandler()); //登陆失败处理器

                }
        );


        //权限拦截
        httpSecurity.authorizeHttpRequests(
                resp -> {
                    resp.requestMatchers("/login","/admin/login").permitAll(); //放行与登陆有关的路径和页面
                    resp.anyRequest().authenticated();
                }
        );

        //配置退出登录
        httpSecurity.logout(
                logout -> {
                    logout.logoutUrl("/admin/logout") //退出登陆路径
                            .logoutSuccessHandler(new MyLogoutSuccessHandler()) //退出登录成功处理器
                            .clearAuthentication(true) //清除权限
                            .invalidateHttpSession(true); //清除session会话
                }
        );

        //异常处理
        httpSecurity.exceptionHandling(
                exception -> {
                    exception.authenticationEntryPoint(new MyAuthenticationEntryPoint()) //未登录异常处理
                            .accessDeniedHandler(new MyAccessDeniedHandler()); //权限不足异常处理
                }
        );

        httpSecurity.cors(); //开放跨域
        httpSecurity.csrf(csrf -> csrf.disable()); //关闭csrf防护
        return httpSecurity.build(); //创建该SecurityFilterChain对象
    }

    //对密码加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
